/*
 * GContest.java
 * Created on 19 juin 07
 *
 * Glacéo Internet Platform
 * http://sourceforge.net/projects/chm/
 *
 * Copyright (c) 2005-2007, Jan Janke (VirtualHockey Project)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hockeo.vhbase.data.dao.contest;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import com.hockeo.vhbase.data.dao.GAbstractDao;
import com.hockeo.vhbase.data.dao.assoc.GAssociation;
import com.hockeo.vhbase.data.dao.season.GSeason;
import com.hockeo.vhbase.data.helper.GContestHistoryType;

/**
 * Base class for all kinds of competitions.
 *
 * @version $Id$
 * @author jjanke
 */
@Entity
@Table( name = "m_contest" )
@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
@DiscriminatorColumn( name = "type", discriminatorType = DiscriminatorType.STRING )
public abstract class GContest extends GAbstractDao implements Iterable<GContestRound>
{
  @Id
  @Column( name = "id" )
  private String                   d_strId;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "association_id" )
  private GAssociation             d_association;

  @Column( name = "impl_class" )
  private String                   d_strImplClass;

  @Column( name = "category" )
  private int                      d_nCategory;

  @Column( name = "num_teams" )
  private int                      d_nNumTeams;

  @Column( name = "prepared" )
  private boolean                  d_fPrepared;

  @OneToMany( mappedBy = "d_contest" )
  @OrderBy( "d_nNum" )
  private List<GContestRound>      d_listContestRounds;

  @OneToMany( mappedBy = "d_contest" )
  @OrderBy( "d_nId" )
  private List<GContestSeasonLink> d_listSeasonLinks;

  /** Default parameterless constructor. */
  protected GContest()
  {}

  /**
   * Returns the coefficient that is used to multiply international ranking
   * (clubs/nations/managers etc.) points depending on the contest they have been obtained
   * in.
   */
  public abstract BigDecimal getRankingCoefficient();

  /**
   * Returns the contest specific history type.
   */
  public abstract GContestHistoryType getHistoryType();

  /**
   * Adds a newly created round to this contest. This method is intentionally package
   * visible because it should only be used by the {@link GContestRound} class itself.
   *
   * @param round the round to be added
   */
  void addRound( GContestRound round )
  {
    if ( d_listContestRounds == null )
      d_listContestRounds = new ArrayList<GContestRound>();

    d_listContestRounds.add( round );
  }

  public GAssociation getAssociation()
  {
    return d_association;
  }

  public int getCategory()
  {
    return d_nCategory;
  }

  public String getImplClass()
  {
    return d_strImplClass;
  }

  public int getNumTeams()
  {
    return d_nNumTeams;
  }

  /**
   * Returns the round that precedes the given one in the contest.
   *
   * @param round the round for which the previous one should be retrieved
   * @return the round that takes place before the given one
   */
  public GContestRound getPreviousRound( GContestRound round )
  {
    if ( !round.getContest().getId().equals( getId() ) )
      throw new IllegalArgumentException( "The round " + round.getId() + " is not part of the contest " + getId() );

    if ( round.getRoundNum() == 1 )
      return null;

    // Retrieve previous round (minus 2 because the round number is 1 based but all rounds
    // are stored in a 0 index based list in here)
    //
    return getContestRounds().get( round.getRoundNum() - 2 );
  }

  /**
   * Returns the round that follows the given one in the contest.
   *
   * @param round the round for which the following one should be retrieved
   * @return the round that takes place after the given one or <code>null</code> if the
   *         given round is the last one
   */
  public GContestRound getNextRound( GContestRound round )
  {
    if ( !round.getContest().getId().equals( getId() ) )
      throw new IllegalArgumentException( "The round " + round.getId() + " is not part of the contest " + getId() );

    if ( round.getRoundNum() >= d_listContestRounds.size() )
      return null;

    // Retrieve following round (we retrieve the round with index equal to the current
    // round number because the indexes are 0-based while the round numbers start with 1)
    //
    return getContestRounds().get( round.getRoundNum() );
  }

  public List<GContestRound> getContestRounds()
  {
    return d_listContestRounds;
  }

  public List<GContestSeasonLink> getSeasonLinks()
  {
    return d_listSeasonLinks;
  }

  /**
   * Returns the contest/season link that is valid for the given season.
   *
   * @param season the season for which to return the matching link
   * @return the matching link or <code>null</code> if there is none
   */
  public GContestSeasonLink getMatchingSeasonLink( GSeason season )
  {
    if ( d_listSeasonLinks == null || d_listSeasonLinks.isEmpty() )
      return null;

    for ( GContestSeasonLink seasonLink : d_listSeasonLinks )
      if ( seasonLink.getFirstSeason().getId() <= season.getId()
          && ( seasonLink.getLastSeason() == null || seasonLink.getLastSeason().getId() >= season.getId() ) )
        return seasonLink;

    return null;
  }

  /**
   * Checks whether the given season is the first within the currently active
   * contest/season link interval.
   *
   * @param season the season for which to check whether it is the first one
   * @return <code>true</code> if the contest is currently active and if the given season
   *         is the first of the currently active interval.
   * @throws IllegalStateException if the contest is currently not active
   */
  public boolean isFirstSeason( GSeason season )
  {
    GContestSeasonLink seasonLink = getMatchingSeasonLink( season );

    if ( seasonLink == null )
      throw new IllegalStateException( "The contest " + getId() + " is not linked to the specified season "
          + season.getId() );

    return seasonLink.getFirstSeason().getId() == season.getId();
  }

  /**
   * Indicates whether this contest has been prepared for the season. I.e. all movedays
   * and matchdays have been created.
   */
  public boolean isPrepared()
  {
    return d_fPrepared;
  }

  /**
   * Sets the "prepared" flag.
   *
   * @param prepared indicates whether this contest has been prepared for the season
   */
  public void setPrepared( boolean prepared )
  {
    d_fPrepared = prepared;
  }

  public String getId()
  {
    return d_strId;
  }

  public String getId( Locale locale )
  {
    return translate( getId(), locale );
  }

  /**
   * Returns the prefix of the contest type icon.
   */
  public abstract String getContestTypeIconPrefix();

  /*
   * @see java.lang.Iterable#iterator()
   */
  public Iterator<GContestRound> iterator()
  {
    return d_listContestRounds.iterator();
  }

  /*
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals( Object obj )
  {
    try
    {
      return d_strId.equals( ( (GContest) obj ).getId() );
    }
    catch ( Exception ex ) // especially ClassCastException(s) may happen
    {
      return false;
    }
  }

  /*
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode()
  {
    return d_strId.hashCode();
  }

  /*
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return d_strId;
  }
}
